package com.proxy.router.interceptor;

import com.proxy.parser.tree.sql.ast.SQLStatement;
import com.proxy.parser.tree.sql.ast.statement.SQLSelectQuery;
import com.proxy.parser.tree.sql.ast.statement.SQLSelectStatement;
import com.proxy.parser.tree.sql.dialect.mysql.ast.statement.MySqlSelectQueryBlock;
import com.proxy.parser.tree.sql.dialect.mysql.visitor.MySqlSchemaStatVisitor;
import com.proxy.parser.tree.sql.SQLParserUtils;
import com.proxy.router.SQLRouteResult;

import java.util.List;

/**
 *  路由查询语句
 *
 *  多表不支持,目前尽可能分析3张表以内的sql语句,太多表的情况,可能要考虑不做结果集合并。
 *
 * Created by liufish on 16/11/1.
 */
public class SelectInterceptor extends BaseInterceptor {


    /**
     * selectQuery 里的 selectList 是选择返回的字段
     * from 也是表示当前查询的表
     *
     *
     */
    @Override
    public void routing(SQLRouteResult result,
                        SQLStatement sqlStatement,
                        MySqlSchemaStatVisitor visitor,
                        List<Object> parameters){



        SQLSelectStatement statement = (SQLSelectStatement)sqlStatement;

        SQLSelectQuery selectQuery = statement.getSelect().getQuery();

        if(selectQuery instanceof MySqlSelectQueryBlock){
            MySqlSelectQueryBlock selectQueryBlock = (MySqlSelectQueryBlock)selectQuery;

            //去除db名称
            SQLParserUtils.removeSchema(selectQueryBlock);

            //如果路由到多个db,就更改分页
            /*SQLLimit sqlLimit =  selectQueryBlock.getLimit();
            if (sqlLimit != null){
                SQLChanger.changeLimit(selectQueryBlock);
            }*/



            selectQueryBlock.getFrom();
            //里面有实现方式
            //MySqlUpdateTableSource  阿里sql,特殊处理,暂时不考虑
            //SQLExprTableSource       单表
            //SQLJoinTableSource       连表
            //SQLSubqueryTableSource    子查询
            //SQLUnionQueryTableSource   合并

            selectQueryBlock.getWhere();



            //select list 对 函数的解析 比如说 avg

            //单表查询情况
            if(visitor.getTables().size() == 1){



                if(visitor.getAggregateFunctions().size() == 0
                        && visitor.getGroupByColumns().size() == 0
                        && visitor.getOrderByColumns().size() == 0)

                System.out.print(statement.toString());

            }

            //两张表的情况
            if(visitor.getTables().size() == 2){

                System.out.print(2);

            }

            //三张表的情况
            if(visitor.getTables().size() == 3){

                System.out.print(3);

            }

            //自连表语句也是多表

        }

    }


    /**
     * 路由最简单的sql语句: 单表 无函数 无group_by  无order_by
     * select * from table where a  = 1
     *
     */
    private void  routing(){

    }



}
